
/**
 * 基于jsonpath进行属性拷贝
 * @param target 目标对象
 * @param source 来源对象
 * @param map 路径映射集合
 */
export function copyByPathMap(target: any, source: any, map: any) {
    if (map) {
        let deleteKeys = [];
        for (const key in map) {
            if (map[key] === '<delete') {
                deleteKeys.push(key);
            } else {
                setByPath(target, key, getByPath(source, map[key]))
            }
        }
        //最后进行删除操作
        for (const key in deleteKeys) {
            delete target[deleteKeys[key]]
        }
    }
}

/**
* 基于jsonpath给对象设置值
* @param obj 对象
* @param path 路径
* @param value 值
* @returns {boolean}
*/
export function setByPath(obj: any, path: any, value: any) {
    //将传入的对象路径字符串拆分为数组
    const pathList = path.split('.');
    if (!obj) {
        obj = {}
    }
    for (let i = 0; i < pathList.length; i++) {
        const key = pathList[i];
        if (i === pathList.length - 1) {
            obj[key] = value;
            return true;
        }
        if (!obj[key]) {
            obj[key] = {}
        }
        obj = obj[key];
    }
}
/**
* 基于jsonpath给对象设置值
* @param obj 对象
* @param path 路径
*/
export function getByPath(obj: any, path: any) {
    //将传入的对象路径字符串拆分为数组
    const pathList = path.split('.');
    if (!obj) {
        return null;
    }
    for (let i = 0; i < pathList.length; i++) {
        const key = pathList[i];
        if (i === pathList.length - 1) {
            return obj[key];
        }
        if (!obj[key]) {
            return null
        }
        obj = obj[key];
    }
}
